﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VoiceRecord : MonoBehaviour
{
#if UNITY_WEBGL
#else
    public AudioClip clip;
    public int samplingRate = 8000;
    public float length;

    int maxRecordTime = 10;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void TryStartRecording()
    {
        try
        {
            Microphone.End(null);
            clip = Microphone.Start(null, false, maxRecordTime, samplingRate);
            print("recording started...");
        }
        catch (Exception e)
        {
            print("TryStartRecording(), failed...");
            print(e);
        }
    }

    public void EndRecording()
    {
        print("recording stopped.");
        int lastPos = Microphone.GetPosition(null);
        if (Microphone.IsRecording(null))
        {
            length = (float)lastPos / samplingRate;
        }
        else
        {
            length = maxRecordTime;
        }

        Microphone.End(null);

        var data = new float[clip.samples * clip.channels];
        clip.GetData(data, 0);
        int floatLen = (int)(length * samplingRate * clip.channels);
        var samplesShort = new short[floatLen];
        for (var index = 0; index < floatLen; index++)
        {
            samplesShort[index] = (short)(data[index] * short.MaxValue);
        }
        byte[] datas = new byte[samplesShort.Length * 2];
        Buffer.BlockCopy(samplesShort, 0, datas, 0, datas.Length);

        SendMessage("OnVoiceRecordBytes", datas, SendMessageOptions.DontRequireReceiver);
//        GetComponent<VoiceRecognition>().Recognize(datas);
    }
#endif
}
